class Item < ActiveRecord::Base
  validates_presence_of :item_name,:item_quantity
  validates_length_of :item_name, :within => 2..255
  validates_length_of :item_detail, :maximum => 10000
  validates_numericality_of :item_quantity, :item_price
  validate :price_must_be_at_least_a_cent
  validate :quantity_must_be_at_least_one
  validate :bought_date_must_not_expired

  belongs_to :brand
  belongs_to :categoty
  belongs_to :subcategory

  attr_accessor :new_brand_name
  before_save :create_brand_from_name

  def create_brand_from_name
    unless new_brand_name.blank?
      self.brand = Brand.find_or_create_by_brand_name(new_brand_name)
    end
  end

  protected
  def price_must_be_at_least_a_cent
    errors.add(:item_price, '价格最少需要在 0.01')if item_price.nil? || item_price < 0.01
  end

  def quantity_must_be_at_least_one
    errors.add(:item_quantity, '数量最少是一个哦')if item_quantity.nil? || item_quantity < 1
  end

  def bought_date_must_not_expired
    errors.add(:item_boughtdate,'您确定您没有购买过期的商品吗')if item_boughtdate > item_expiredate
  end

end
